import json

from apps.db import db
from apps.model import BankSideInfo, BorrowerInfo, BankSideExtendInfo
from apps.model.diya_person import DiyaPerson
from apps.seleuinms.process.common import request3
from apps.seleuinms.utils import get_value

from apps.utils import curtime


class Shangdaitong(object):
    """商贷通"""

    def __init__(self, item: dict, cookies):
        self.item = item
        self.cookies = cookies
        extensionFieldOne = json.loads(self.item.get('extensionFieldOne'))
        self.query = {
            'businessKey': item.get('businessKey'),
            'taskId': item.get('taskId'),
            'custId': extensionFieldOne.get('custId')
        }

    def get_data(self, state='waitUpload'):
        """抽取极速贷合同信息"""
        # 获取合同信息
        from apps.app import app
        with app.app_context():
            base_info = {
                'custom_name': self.item.get('customName'),
                'baseWork_flow_name': self.item.get('baseWorkFlowName'),
                'business_key': self.item.get('businessKey'),
                'start_org_code': self.item.get('start_org_code'),
                'option_user_name': self.item.get('option_user_name'),
                'description': self.item.get('processDefineName'),
                'create_time': curtime(),
                'task_id': self.item.get('taskId'),
                'cust_id': self.query.get('custId'),
                'state': state,
            }
            bank_info: BankSideInfo = BankSideInfo(**base_info)

            # 合同列表
            contracts = self.get_contract_list()
            # 抵押物列表
            collats = self.get_colla_list()

            for contract in contracts:
                init = self.get_init()
                extend = BankSideExtendInfo(**init)
                extend.contract_id = bank_info.id

                # 借款人
                self.get_common_borrower(extend.id)
                # 通过合同编号查找抵押：
                for collat in collats:
                    if len(collats) > 1:
                        if collat.get('contractNo') is not None:
                            if collat.get('contractNo') != contract.get('conactNo'):
                                continue
                        elif collat.get('collatId') != contract.get('extendNo'):
                            continue
                    detail = self.get_colla_base_info(collat.get('collatId'))
                    extend.contract_no = contract.get('contractNo', contract.get('conactNo'))
                    if contract.get('contractBgnStageTime') is not None:
                        extend.contract_start_date = contract.get('contractBgnStageTime')
                        extend.contract_end_date = contract.get('contractEndStageTime')
                    else:
                        extend.contract_start_date = contract.get('guarClaimBgnDate')
                        extend.contract_end_date = contract.get('guarClaimDlineDate')
                    extend.house_cert_no = collat.get('phyDocNo')
                    extend.build_marea = detail.get('buildMarea')
                    extend.total_price = detail.get('prelimAssessIdentifyVal')
                    extend.contract_amt = contract.get('limitAmt')
                    if contract.get('houseLocated') is not None:
                        extend.house_located = contract.get('houseLocated')
                    else:
                        extend.house_located = detail.get('locLocDtlDesc')
                    extend.house_whole_located = detail.get('locLocDtlDesc')
                    extend.collat_id = collat.get('collatId')
                    extend.dkfs = detail.get('ownershipVchrTypeCode')

                    extend.save()

                    # 根据押品获取当前押品权利人作为抵押人
                    self.get_colla_owners(collat.get('collatId'), extend.id)
                    break

            bank_info.save()
            db.session.commit()

    def get_init(self):
        return {
            'dysw': '1',
            # 担保范围：
            'dbfw': '主债权以及附属于主债权的一切费用，包括但不限于主债权.利息.违约金.损害赔偿金.实现债权的诉讼费用.执行费用.律师费用等',
            # 证明登记
            'zmdj': '无',
            # 登薄备注
            'dbbz': '无',
            # 是否组合贷
            'is_combo': '0',
            # 抵押权人
            'qlr': '中国邮政储蓄银行股份有限公司盐城市分行',
            # 抵押权利人证件号
            'qlr_cert_no': '91320902674401302F',
            # 抵押方式
            'dy_method': '最高额抵押',
            # 贷款方式
            'loan_method': '商业',
            'dyqr_tel': '15862011018'
        }

    def get_contract_list(self):
        """查看授信合同列表"""
        url = 'http://22.230.57.12:8080/creaditContract/findContractList'
        params = {
            'busiNo': self.item.get('businessKey'),
            'deledFlag': '0',
        }
        res = request3(url, params, self.cookies)
        # 所有抵押合同，非主合同
        return [item for item in get_value(res, 'data.grid') if item.get('contractType') == '02']

    def get_colla_list(self):
        url = 'http://22.230.57.12:8080/realestateCase/findRealestateCollateList'
        params = {
            'busiNo': self.item.get('businessKey'),
            'provCode': '3200',
            'taskId': self.item.get('taskId'),
            '_curMenuCode': None,
        }
        res = request3(url, params, self.cookies)
        return get_value(res, 'data.grid')

    def get_colla_base_info(self, colla_id):
        """根据押品id, 获取押品详情， 其中包括评估价格"""
        info = {}
        url = 'http://22.230.57.12:8080/guaranteeBaseInfo/getGuaranteeBaseInfo'
        params = {
            'collatId': colla_id,
            'provCode': '3200',
        }
        response = request3(url, params, self.cookies)
        info['prelimAssessIdentifyVal'] = response.get('data').get('psbcCfmVal')
        """获取当前押品不动产权证书"""
        url = "http://22.230.57.12:8080/warrantInfo/queryWarrantInfoList"
        params = {
            'collatId': colla_id,
            'provCode': '3200',
            'deledFlag': '0'
        }
        response = request3(url, params, self.cookies)
        data = response.get('data')
        # 所有权
        for item in data:
            if item.get('ownershipVchrTypeCode') == '45':  # 不动产权证书 39： 国有土地使用证/集体土地建设使用证编号 # 38 房屋所有权证明
                info['ownershipVchrTypeCode'] = item.get('ownershipVchrTypeCode')
                info['phyDocNo'] = item.get('phyDocNo')
                break
        if info.get('phyDocNo') is None:
            for item in data:
                if item.get('ownershipVchrTypeCode') == '38':  # 不动产权证书 39： 国有土地使用证/集体土地建设使用证编号 # 38 房屋所有权证明
                    info['phyDocNo'] = item.get('phyDocNo')
                    info['ownershipVchrTypeCode'] = item.get('ownershipVchrTypeCode')
                    f = [d for d in data if d.get('ownershipVchrTypeCode') == '39']
                    if f is None or len(f) < 1:
                        raise Exception(500, '房屋所有权证书 未找到土地使用证')
                    break
        """获取押品坐落，押品建筑面积"""
        url = 'http://22.230.57.12:8080/housePropertyInfo/getHousePropertyInfo'
        response = request3(url, params, self.cookies)
        info['buildMarea'] = response.get('data').get('buildMarea')
        info['locLocDtlDesc'] = response.get('data').get('locLocDtlDesc')
        return info

    def get_colla_owners(self, colla_id, extend_id=None):
        """根据押品id, 查询抵押人信息"""
        url = 'http://22.230.57.12:8080/guaranteeOwnShareInfo/queryGuaranteeOwnShareInfoList'
        params = {
            'collatId': colla_id,
            'provCode': '3200',
            'deledFlag': '0',
        }
        response = request3(url, params, self.cookies)
        res = response.get('data')
        for item in res:
            diya = {
                # 联系方式
                "telphone": item.get('telNo'),
                'name': item.get('ownerName'),
                # 身份证上的地址
                'address': item.get('ownerResidAddr'),
                # 证件类型：
                'cert_type': '10',  # 身份证
                # 证件号：
                'cert_no': item.get('certNo')
            }
            d = DiyaPerson(**diya)
            d.extend_id = extend_id
            d.save()

    def get_common_borrower(self, extend_id):
        """获取共同借款人"""
        url = 'http://22.230.57.12:8080/borrowerManage/borrowerInfo/get'
        cust_id = self.query.get('custId')
        taskId = self.item.get('taskId')
        params = {
            'taskId': taskId,
            'custId': cust_id,
            '_curMenuCode': 'index',
        }
        res = request3(url, params, self.cookies)
        res = res.get('data').get('borrowerInfo')
        if res.get('custName') is not None:
            # 主借人
            borrower_info = {
                # 义务人类型： main: 借款人 sub: 借款人配偶
                'type': 'main',
                # 联系方式
                "telphone": res.get('contTelContact'),
                'name': res.get('custName'),
                'no': res.get('custNo'),
                # 身份证上的地址
                'address': res.get('hsRegAddr'),
                'cust_id': res.get('custId'),
                # 证件类型：
                'cert_type': res.get('certType'),  # '10', # 身份证
                # 证件号：
                'cert_no': res.get('certNo'),
                'extend_id': extend_id,
            }
            BorrowerInfo(**borrower_info).save()
        # 配偶
        url = 'http://22.230.57.12:8080/borrowerManage/borrowerSpouseInfo/get'
        params = {
            'custId': cust_id,
            'taskId': taskId,
            '_curMenuCode': 'index',
        }
        res = request3(url, params, self.cookies)
        res = get_value(res, 'data.borrowerSpouseInfo')
        if res is not None and res.get('custName') is not None:
            # 具有配偶信息， 共同借款人
            borrower_info = {
                # 义务人类型： main: 借款人 sub: 借款人配偶
                'type': 'sub',
                # 联系方式
                "telphone": res.get('contTelContact'),
                'name': res.get('custName'),
                'no': res.get('custNo'),
                # 身份证上的地址
                'address': res.get('hsRegAddr'),
                'cust_id': res.get('custId'),
                # 证件类型：
                'cert_type': res.get('certType'),  # '10', # 身份证
                # 证件号：
                'cert_no': res.get('certNo'),
                'extend_id': extend_id,
            }
            BorrowerInfo(**borrower_info).save()
            return

        url = 'http://22.230.57.12:8080/borrowerManage/coBorrowerInfoWithSpouse/get'
        params = {
            'busiNo': self.item.get('businessKey'),
            'taskId': taskId,
            '_curMenuCode': 'index',
        }
        res = request3(url, params, self.cookies)
        res = get_value(res, 'data')
        if res is not None and len(res) > 0:
            res = res[0].get('coBorrowerInfo')
            borrower_info = {
                # 义务人类型： main: 借款人 sub: 共同借款人
                'type': 'sub',
                # 联系方式
                "telphone": res.get('contTelContact'),
                'name': res.get('custName'),
                'no': res.get('custNo'),
                # 身份证上的地址
                'address': res.get('hsRegAddr'),
                'cust_id': res.get('custId'),
                # 证件类型：
                'cert_type': res.get('certType'),  # '10', # 身份证
                # 证件号：
                'cert_no': res.get('certNo'),
                'extend_id': extend_id,
            }
            BorrowerInfo(**borrower_info).save()
        pass


class NormalLoan(Shangdaitong):

    def get_data(self, state='waitUpload'):
        """抽取极速贷合同信息"""
        # 获取合同信息
        from apps.app import app
        with app.app_context():
            base_info = {
                'custom_name': self.item.get('customName'),
                'baseWork_flow_name': self.item.get('baseWorkFlowName'),
                'business_key': self.item.get('businessKey'),
                'start_org_code': self.item.get('start_org_code'),
                'option_user_name': self.item.get('option_user_name'),
                'description': self.item.get('processDefineName'),
                'create_time': curtime(),
                'task_id': self.item.get('taskId'),
                'cust_id': self.query.get('custId'),
                'state': state,
            }
            bank_info: BankSideInfo = BankSideInfo(**base_info)

            # 合同列表
            contracts = self.get_contract_list()
            # 抵押物列表
            collats = self.get_colla_list()

            for contract in contracts:
                init = self.get_init()
                extend = BankSideExtendInfo(**init)
                extend.contract_id = bank_info.id

                # 借款人
                self.get_common_borrower(extend.id)
                # 通过合同编号查找抵押：
                for collat in collats:
                    if len(collats) > 1:
                        if collat.get('contractNo') is not None:
                            if collat.get('contractNo') != contract.get('conactNo'):
                                continue
                        elif collat.get('collatId') != contract.get('extendNo'):
                            continue
                    detail = self.get_colla_base_info(collat.get('collatId'))
                    extend.contract_no = contract.get('contractNo', contract.get('conactNo'))
                    if contract.get('contractBgnStageTime') is not None:
                        extend.contract_start_date = contract.get('contractBgnStageTime')
                        extend.contract_end_date = contract.get('contractEndStageTime')
                    else:
                        extend.contract_start_date = contract.get('guarClaimBgnDate')
                        extend.contract_end_date = contract.get('guarClaimDlineDate')
                    extend.house_cert_no = collat.get('phyDocNo')
                    extend.build_marea = detail.get('buildMarea')
                    extend.total_price = detail.get('prelimAssessIdentifyVal')
                    extend.contract_amt = contract.get('limitAmt')
                    if contract.get('houseLocated') is not None:
                        extend.house_located = contract.get('houseLocated')
                    else:
                        extend.house_located = detail.get('locLocDtlDesc')
                    extend.house_whole_located = detail.get('locLocDtlDesc')
                    extend.collat_id = collat.get('collatId')
                    extend.dkfs = detail.get('ownershipVchrTypeCode')

                    extend.save()

                    # 根据押品获取当前押品权利人作为抵押人
                    self.get_colla_owners(collat.get('collatId'), extend.id)
                    break

            bank_info.save()
            db.session.commit()

    def get_contract_list(self):
        """查看授信合同列表"""
        url = "http://22.230.57.12:8080/single/getLonApplyLoanMain"
        # 查询贷款申请
        params = {
            'loanApplyId': self.item.get('businessKey'),
            'loanProdtId': self.item.get('productId'),
            'taskId': self.item.get('taskId'),
            '_curMenuCode': None,
        }
        data = request3(url, params, self.cookies).get('data')
        other = data.get('othBankHouFundLoanAmt', 0)

        url = 'http://22.230.57.12:8080/realEststeQuiry/findLoanContract'
        params = {
            'loanApplyId': self.item.get('businessKey'),
            'custId': self.query.get('custId'),
            'provCode': '3200',
            'taskId': self.item.get('taskId'),
            '_curMenuCode': None,
        }
        data = request3(url, params, self.cookies).get('data')
        data['limitAmt'] = data.get('contractAmt') + other
        return [data]

    def get_init(self):
        lond_info = self.get_lon_apply_loan_main().get('data')
        prodt_name = lond_info.get('prodtName')
        """
            一手房抵押方式为一般抵押
            二手房以及其他的抵押方式为最高额抵押
        """
        dy_method = '一般抵押'
        if '个人一手' not in prodt_name:
            dy_method = '最高额抵押'

        # 是否组合贷
        if lond_info.get('othBankHouFundLoanFlag') != '0':  # 是
            othBankHouFundLoanFlag = '1'
            qlr = '中国邮政储蓄银行股份有限公司盐城市分行/盐城市住房公积金管理中心'
            qlr_cert_no = '91320902569196GBH'
            # 贷款方式
            loan_method = '组合'
        else:  # 否
            othBankHouFundLoanFlag = '0'
            qlr = '中国邮政储蓄银行股份有限公司盐城市分行'
            qlr_cert_no = '91320902674401302F'
            # 贷款方式
            loan_method = '商业'
        return {
            'dysw': '1',
            # 担保范围：
            'dbfw': '主债权以及附属于主债权的一切费用，包括但不限于主债权.利息.违约金.损害赔偿金.实现债权的诉讼费用.执行费用.律师费用等',
            # 证明登记
            'zmdj': '无',
            # 登薄备注
            'dbbz': '无',
            # 是否组合贷
            'is_combo': othBankHouFundLoanFlag,
            # 抵押权人
            'qlr': qlr,
            # 抵押权利人证件号
            'qlr_cert_no': qlr_cert_no,
            # 抵押方式
            'dy_method': dy_method,
            # 贷款方式
            'loan_method': loan_method,
            'dyqr_tel': '15862011018'
        }

    def get_colla_list(self):
        url = 'http://22.230.57.12:8080/realestateCase/findRealestateCollateList'
        params = {
            'busiNo': self.item.get('businessKey'),
            'provCode': '3200',
            'taskId': self.item.get('taskId'),
            '_curMenuCode': None,
        }
        res = request3(url, params, self.cookies)
        return get_value(res, 'data.grid')

    def get_lon_apply_loan_main(self):
        """查询贷款申请信息"""
        url = "http://22.230.57.12:8080/single/getLonApplyLoanMain"
        """
        loanApplyId: jkbh3299960Q210104002279
        loanProdtId: P30102010004
        taskId: 68f86482a4f241a3b41063a3251e94b0
        _curMenuCode:
        """
        params = {
            'loanApplyId': self.item.get('businessKey'),
            'loanProdtId': self.item.get('productId'),
            'taskId': self.item.get('taskId'),
            '_curMenuCode': None,
        }
        return request3(url, params, self.cookies)
